<template>
  <view class="flex" v-if="paytype != 1">
    <!-- 取消订单 -->
    <template v-if="cancel || orderStatus == 6">
      <button
        class="Btn bg-white text-base text-black leading-[60rpx] h-[60rpx] rounded-full"
        @click.stop="handleOrderCancel(orderId)"
      >
        取消订单
      </button>
    </template>

    <!-- 删除订单 -->
    <template v-if="orderStatus == 4 || del">
      <button
        class="Btn bg-white text-base text-black leading-[60rpx] h-[60rpx] rounded-full"
        @click.stop="handleOrderDel(orderId)"
      >
        删除订单
      </button>
    </template>
    <!-- 售后 -->

    <template v-if="orderStatus == 999">
      <button
        class="Btn evaluate bg-white text-sm text-muted leading-[60rpx] h-[60rpx] rounded-full"
        @click.stop="goPage('/bundle/pages/shouhou/index')"
      >
        售后
      </button>
    </template>

    <!-- 去评价 -->
    <template v-if="evaluate">
      <button
        class="Btn evaluate bg-white text-sm text-muted leading-[60rpx] h-[60rpx] rounded-full"
        @click.stop="goPage('/bundle/pages/evaluate_list/index')"
      >
        去评价
      </button>
    </template>

    <!-- 联系师傅 -->
    <template v-if="contact">
      <button
        class="Btn flex-1 mr-2 bg-white text-sm text-black leading-[70rpx] h-[70rpx] rounded-full"
        @click.stop="handleContactMobile()"
      >
        联系师傅
      </button>
    </template>

    <!-- 去支付 -->
    <template v-if="pay">
      <button
        class="bg-primary text-lg ml-[20rpx] text-white leading-[60rpx] h-[60rpx] rounded-full"
        @click.stop="handlePayment"
      >
        去支付
      </button>
    </template>
    <!-- 立即预约 -->
    <template v-if="orderStatus == 6 && paytype != 2">
      <button
        class="bg-primary text-lg ml-[20rpx] text-white leading-[60rpx] h-[60rpx] rounded-full"
        @click.stop="goinfo"
      >
        立即预约
      </button>
    </template>

    <!-- 确认服务 -->
    <template v-if="confirmService">
      <button
        class="bg-primary text-lg text-white leading-[60rpx] h-[60rpx] rounded-full"
        @click.stop="handleConfirmService(orderId)"
      >
        确认服务
      </button>
    </template>
    <template v-if="paytype == 2">
      <button
        class="bg-primary text-lg text-white leading-[60rpx] h-[60rpx] rounded-full"
        @click.stop="retqryy"
      >
        确认预约
      </button>
    </template>

    <!-- 核销订单 -->

    <template v-if="verification">
      <view class="flex justify-around">
        <button
          v-if="isphoneFromNumber"
          class="flex-1 bg-primary text-sm text-white leading-[70rpx] h-[70rpx] rounded-full"
          @click.stop="handleContactMobile"
        >
          联系用户
        </button>
        <button
          class="flex-1 bg-primary text-sm text-white leading-[70rpx] h-[70rpx] rounded-full"
          @click.stop="confirmVerification"
        >
          确认核销
        </button>
        <!-- <button
                    class="Btn flex-1 mr-2 bg-white text-sm text-black leading-[70rpx] h-[70rpx] rounded-full"
                    @click.stop="showInputCode = true"
                >
                    手动核销码
                </button> -->
        <!-- #ifdef MP -->
        <!-- <button
                    class="flex-1 bg-primary text-sm text-white leading-[70rpx] h-[70rpx] rounded-full"
                    @click.stop="handleScanQRCode"
                >
                    扫码核销
                </button> -->
        <!-- #endif -->
      </view>

      <!-- 手动输入核销码MODAL -->
      <u-modal
        ref="uModalInput"
        v-model="showInputCode"
        show-cancel-button
        confirmColor="#6B3DA3"
        confirm-text="确定"
        @confirm="inputOrderCode"
        @cancel="handleCancel"
        title="手动核销"
      >
        <view class="slot-content justify-center" style="padding: 60rpx 40rpx">
          <u-input
            type="number"
            v-model="code"
            :border="true"
            placeholder="请输入核销码"
            style="width: 100%"
          />
        </view>
      </u-modal>
    </template>
  </view>
  <u-popup
    v-model="showConfirmPop"
    mode="center"
    height="500"
    border-radius="14"
  >
    <view class="text-center w-[560rpx] pt-[40rpx]">
      <view class="w-[160rpx] h-[160rpx] px-[200rpx]">
        <u-image width="160" height="160" :src="goodsImage" />
      </view>
      <view class="mt-[20rpx] truncate">{{ goodsName }}</view>
      <view class="mt-[10rpx] mb-[40rpx] text-[#f36161]"
        >完成服务请点击确认</view
      >
      <button
        class="flex-1 bg-primary text-sm text-white leading-[70rpx] h-[70rpx] rounded-full mx-[40rpx]"
        @click.stop="confirmVerification"
      >
        确认核销
      </button>
    </view>
  </u-popup>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import {
  apiOrderCancel,
  apiStaffOrderConfirmService,
  apiStaffOrderVerification,
  apiOrderDel,
  apicallStaffPhone,
} from "@/api/order";
import { PayFromType } from "@/enums/appEnums";
import { useUserStore } from "@/stores/user";
import { storeToRefs } from "pinia";
import { getClient } from "@/utils/client";
import { isWeixinClient } from "@/utils/client";

const emit = defineEmits(["refresh", "backRefresh", "refreshQryy"]);
const userStore = useUserStore();
const { userInfo } = storeToRefs(userStore);

const props = withDefaults(
  defineProps<{
    orderId?: any; // 订单ID
    orderSn?: any; // 订单编号
    cancel?: boolean | number | null; // 取消订单
    evaluate?: boolean | number | null; // 评价
    pay?: boolean | number | null; // 支付
    confirmService?: boolean | number | null; // 确认服务
    verification?: boolean | number | null; // 核销订单
    goodsImage?: string | null; // 商品图片
    goodsName?: string | null; // 商品名称
    order_amount?: string | null; // 订单金额
    mobile?: number | string | null; // 手机号码
    contact?: number | boolean; // 联系师傅
    staffId?: any;
    type?: number | null; // 支付方式
    orderStatus?: number | string | null; // 订单状态;0-待支付;1-预约中;2-服务中;3-已完成;4-已关闭
    del?: boolean | number | null; // 删除订单
    cancelTime?: number | null;
    phoneToNumber?: number | string | null;
    phoneFromNumber?: number | string | null;
    isphoneFromNumber?: number | boolean; // 联系师傅
    paytype?: number | boolean;
  }>(),
  {
    orderId: "",
    orderSn: "",
    cancel: false,
    evaluate: false,
    pay: false,
    confirmService: false,
    verification: false,
    goodsImage: "",
    goodsName: "",
    del: false,
    contact: false,
    mobile: "",
    staffId: "",
    type: 2,
    orderStatus: "",
    cancelTime: 0,
    phoneFromNumber: "",
    phoneToNumber: "",
    isphoneFromNumber: false,
    paytype: 0,
  }
);

const code = ref<number | string>(""); // 输入核销码
const showInputCode = ref<boolean>(false); // 显示(输入核销码)：是 | 否

// 页面跳转
const goPage = (url: string) => {
  uni.navigateTo({ url });
};

// 取消订单
const handleOrderCancel = async (id: number | string): Promise<void> => {
  const modelRes = await uni.showModal({
    title: "温馨提示",
    content: "确认取消该订单吗？",
  });
  if (modelRes.cancel) return;

  try {
    await apiOrderCancel({
      id,
      userId: userInfo.value.id,
      source: getClient(),
    });
    uni.$u.toast("操作成功");
    emit("refresh");
  } catch (error) {
    console.log("错误信息：", error, props.orderId);
  }
  emit("refresh");
};

// 删除订单
const handleOrderDel = async (id: number | string): Promise<void> => {
  const modelRes = await uni.showModal({
    title: "温馨提示",
    content: "确认删除该订单吗？",
  });
  if (modelRes.cancel) return;

  try {
    await apiOrderDel({ id });
    uni.$u.toast("操作成功");
  } catch (error) {
    console.log("错误信息：", error, props.orderId);
  }

  emit("refresh");
};

// 支付
const handlePayment = () => {
  const param = {
    order_id: props.orderId,
    from: PayFromType.ORDER,
    order_amount: props.order_amount,
    cancelTime: props.cancelTime,
  };
  uni.$emit("payment", param);
};
// 联系师傅
const handleContactMobile = () => {
  console.log("目前还没有师傅", props, "-----------", props.phoneToNumber);
  if (!props.phoneFromNumber || !props.phoneToNumber) {
    uni.$u.toast("目前还没有师傅");
    return;
  }
  let params = {
    phoneFromNumber: props.phoneFromNumber,
    phoneToNumber: props.phoneToNumber,
  };
  apicallStaffPhone(params).then((res) => {
    console.log(res, "resd");
    if (res == null) {
      uni.$u.toast("系统繁忙，请稍后再联系~");
    } else {
      uni.makePhoneCall({
        phoneNumber: res, //仅为示例
      });
    }
  });
};
// 确认服务
const handleConfirmService = async (id: number | string): Promise<void> => {
  const modelRes = await uni.showModal({
    title: "温馨提示",
    content: "确认服务该订单吗？",
  });
  if (modelRes.cancel) return;
  await apiStaffOrderConfirmService({ id });
  uni.$u.toast("操作成功");
  emit("refresh");
};
const retqryy = () => {
  emit("refreshQryy");
};
// 扫码
const handleScanQRCode = () => {
  // #ifdef H5
  if (!isWeixinClient()) return uni.$u.toast("h5暂不支持扫码");
  showInputCode.value = true;
  // #endif

  // #ifdef MP
  wx.scanCode({
    success: (data) => {
      code.value = data.result;
      showConfirmPop.value = true;
    },
    fail: (err) => {
      console.log(err);
    },
  });
  // #endif
};

// 确认核销
const showConfirmPop = ref(false);
const confirmVerification = async () => {
  try {
    // await apiStaffOrderVerification({ id: props.orderId, code: code.value })
    await apiStaffOrderVerification({ id: props.orderId });
    code.value = "";
    uni.$u.toast("订单核销成功");
    showConfirmPop.value = false;
    emit("refresh");
  } catch (error) {
    uni.$u.toast(error);
  }
};
// 手动输入核销码
const inputOrderCode = async (): Promise<void> => {
  if (code.value === "") return uni.$u.toast("请输入核销码");
  try {
    await apiStaffOrderVerification({ id: props.orderId, code: code.value });
    uni.$u.toast("订单核销成功");
    emit("refresh");
  } catch (error) {
    console.log(error);
  }
  code.value = "";
};

// 取消核销码弹框
const handleCancel = () => {
  code.value = "";
  emit("refresh");
};

const goinfo = () => {
  uni.redirectTo({
    url: `/pages/order_detail/index?id=` + props.orderId + "&paytype=2",
  });
};
</script>

<style lang="scss" scoped>
.Btn {
  border: 1px solid rgba(187, 187, 187, 1);
  background-color: rgba(255, 255, 255, 1);
  color: rgba(16, 16, 16, 1);
  text-align: center;
}
.evaluate {
  border: 1px solid $u-type-primary;
  color: $u-type-primary;
}

.bg-primary {
  background-color: rgba(132, 86, 255, 1) !important;
}
.evaluate {
  border: 1rpx solid rgba(34, 34, 34, 0.2);
  color: #8456ff;
}
</style>
